﻿using Com.JunCaiSoft.AutoMapper;
using Com.JunCaiSoft.Common.Controller;
using Com.JunCaiSoft.Common.ExchangeData;
using Com.JunCaiSoft.Common.Model;
using Com.JunCaiSoft.Law.Dto;
using Com.JunCaiSoft.Law.Entity;
using Com.JunCaiSoft.Law.IDao;
using Com.JunCaiSoft.Law.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Com.JunCaiSoft.API.Law.Controllers
{
    /// <summary>
    /// 案件跟踪管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class CaseHandleController : BaseController<CaseHandleView, CaseHandleItem, CaseHandle, Guid>
    {
        public CaseHandleController(ICaseHandleDao caseDao) : base(caseDao)
        {

        }
        /// <summary>
        /// 按跟踪ID单个删除
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete]
        public override async Task<ActionResult> DeleteSingleAsync(Guid Id)
        {
            try
            {
                await DaoAsync.dbContext.Database.BeginTransactionAsync();
                int result = await DaoAsync.DeleteListAsync<CaseHandle>(x => x.Id == Id);

                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                DaoAsync.dbContext.Database.CommitTransaction();
            }
        }
        /// <summary>
        /// 按跟踪ID批量删除
        /// </summary>
        /// <param name="DeleteList"></param>
        /// <returns></returns>
        [HttpPatch]
        public virtual async Task<ActionResult> DeleteList(IEnumerable<Guid> DeleteList)
        {
            try
            {
                await DaoAsync.dbContext.Database.BeginTransactionAsync();

                int result = await DaoAsync.DeleteListAsync<CaseHandle>(x => DeleteList.Contains(x.Id));

                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                DaoAsync.dbContext.Database.CommitTransaction();
            }
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize"></param>
        /// <param name="keyword">关键字</param>
        /// <returns></returns>
        [HttpGet]
        public virtual async Task<ActionResult> ListByPageAsync(int pageIndex, int pageSize, String keyword)
        {
            try
            {
                var columns = @" ch.Id,
	                             ch.Num,
	                             ch.NumCode,
	                             pj.Name CaseProject,
	                             ch.Plaintiff,
	                             ch.Defendant,
	                             ch.IsPrincipalComplaint,
	                             ch.CaseCode,
	                             ch.Solve,
	                             ch.CaseStage,
	                             ch.Agent,
	                             ch.CaseStatus,
	                             ch.AccpectOffice,
	                             ch.Judge,
	                             ch.JudgeConnect,
	                             ch.Lawyer,
	                             ch.LawyerConnect,
	                             ch.LitigationAmount,
	                             ch.JudgmentAmount,
	                             ch.StopLossAmount,
	                             ch.JudgmentTime,
	                             ch.IsAppeal,
	                             ch.IsNeedExcute,
	                             cm.IsFinishExcute,
	                             u.RealName,
	                             ch.Document,
	                             ch.CreateTime,
	                             SUM ( pv.Amount ) PreservationAmount,
	                             SUM ( fm.Amount ) FreezeMoney,
	                             SUM ( fm.FactFreeze ) FactFreezeMoney,
	                             SUM ( ufm.Amount ) UnFreezeMoney  ";

                var tables = @" CaseHandle ch
	                                LEFT JOIN CaseMain cm ON ch.CaseMainInfo = cm.Id
	                                LEFT JOIN Project pj ON cm.CaseProject = pj.Id
	                                LEFT JOIN Preservation pv ON cm.Id = pv.CaseMainInfo
	                                LEFT JOIN FreezeMoney fm ON pv.Id = fm.PreservationInfo
	                                LEFT JOIN UnFreezeMoney ufm ON fm.Id = ufm.FreezeInfo
	                                LEFT JOIN [User] u ON ch.RegistOperator = u.Id  ";

                var where = @" 1 = 1 ";

                List<SqlParameter> casehandleParams = new List<SqlParameter>() { };

                if (!String.IsNullOrEmpty(keyword))
                {

                    where += " AND ch.CaseCode like @CaseCodeOrProjectName OR pj.Name like @CaseCodeOrProjectName ";

                    SqlParameter QueryCaseHandle = new SqlParameter("@CaseCodeOrProjectName", "%" + keyword + "%");

                    casehandleParams.Add(QueryCaseHandle);

                }

                where += @" GROUP BY
	                            ch.Id,
	                            ch.Num,
	                            ch.NumCode,
	                            pj.Name,
	                            ch.Plaintiff,
	                            ch.Defendant,
	                            ch.IsPrincipalComplaint,
	                            ch.CaseCode,
	                            ch.Solve,
	                            ch.CaseStage,
	                            ch.Agent,
	                            ch.CaseStatus,
	                            ch.AccpectOffice,
	                            ch.Judge,
	                            ch.JudgeConnect,
	                            ch.Lawyer,
	                            ch.LawyerConnect,
	                            ch.LitigationAmount,
	                            ch.JudgmentAmount,
	                            ch.StopLossAmount,
	                            ch.JudgmentTime,
	                            ch.IsAppeal,
	                            ch.IsNeedExcute,
	                            cm.IsFinishExcute,
	                            u.RealName,
	                            ch.Document,
	                            ch.CreateTime ";

                var tmpResultList = await DaoAsync.QuerySQLByPageQuickAsync<CaseHandleItemDto>(pageIndex, pageSize, " ch.CreateTime desc ", columns, tables, where, casehandleParams.Select(x => ((ICloneable)x).Clone()).ToArray());

                var resultList = new QueryData<CaseHandleItem>();

                var itemList = new List<CaseHandleItem>();

                resultList.totalCount = tmpResultList.totalCount;

                tmpResultList.items.ToList().ForEach(item => itemList.Add(item.MapTo<CaseHandleItem>()));

                resultList.items = itemList;

                return await Task.Run(() => Content(JsonConvert.SerializeObject(resultList)));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        /// <summary>
        /// 创建跟踪信息
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public override async Task<ActionResult> CreateAsync(CaseHandleView entity)
        {
            try
            {
                DaoAsync.dbContext.Database.BeginTransaction();

                var saveone = entity.MapTo<CaseHandle>();
                var result = await DaoAsync.InsertAsync(saveone);

                DaoAsync.dbContext.Database.CommitTransaction();
                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                throw e;
            }

        }
        /// <summary>
        /// 更新跟踪信息
        /// </summary>
        /// <param name="entityModel"></param>
        /// <returns></returns>
        [HttpPut]
        public override async Task<ActionResult> UpdateAsync(UpdateEntity<CaseHandleView> entityModel)
        {
            DaoAsync.dbContext.Database.BeginTransaction();

            var saveone = entityModel.entity.MapTo<CaseHandle>();
            var result = await DaoAsync.UpdateAsync(saveone, entityModel.Id);

            DaoAsync.dbContext.Database.CommitTransaction();
            return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
        }
    }
}
